package cn.wolfcode.web.controller;

import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utli.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @ResponseBody
    @RequestMapping("/reload")
    private JsonResult reload(){
        try {
            permissionService.reload();
            return new JsonResult(true,"加载成功");
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"加载失败");
        }
    }

    // 处理查询所有部门请求
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Permission> pageResult = permissionService.query(qo);
        model.addAttribute("pageResult", pageResult);
        // 找视图 /WEB-INF/views/permission/list.jsp }
        return "/permission/list";
    }

    // 处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                permissionService.deleteByPrimaryKey(id);
            }
            return new JsonResult(true,"删除成功");
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) { // 表示去修改
            Permission permission = permissionService.selectByPrimaryKey(id);
            model.addAttribute("permission", permission);
        }
        // 让浏览器重新发一次请求
        return "/permission/input";
    }

    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission ) {
        if (permission.getId() == null) {
            // 新增
            permissionService.insert(permission);
        } else {// 修改
            permissionService.updateByPrimaryKey(permission);
            // 让浏览器重新发一次请求
        }
        return "redirect:/permission/list.do";
    }

}
